#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    查询所有房间
    Add By : cdj <e4ting@qq.com> 2021-07-14 17:57:18
"""
from flask_restful import Resource
from flask         import redirect,request,make_response

# from urllib.parse import urlparse

from e4ting         import util,log
from core.cache     import RoomCache
from models.mysqls  import db,ModelRoom
from core.game.room import Room
import json
# from core.webhook.events import EventBaitPot
# from core.webhook.hooks  import HookSender

class WebJoinRoom(Resource):
    """ 加入房间 """

    def post(self, id=None):
        """ 加入房间 """

        roomid = request.json.get("room", "")
        robot  = request.json.get("robot", "")

        seat_num = request.json.get("seat_num", None)
        uid = request.user["uid"]

        cache  = RoomCache(roomid)
        if not cache.exists():
            return ApiErr(code=404, msg="房间不存在")

        if seat_num == None:
            return ApiErr(code=400, msg="座位号不能为空")

        if not ( 0 <= seat_num <= 9):
            return ApiErr(code=400, msg="座位号不合法")

        # 是否已在另一个房间
        # if not ( 0 <= seat_num <= 9):
        #     return ApiErr(code=400, msg="座位号不合法")

        # 座位是否已有人
        # if not ( 0 <= seat_num <= 9):
        #     return ApiErr(code=400, msg="座位号不合法")

        seat_str = str(seat_num)
        # 加载坐席表
        seats = json.loads(cache.seats or "{}")
        log.info(seats)

        if robot:
            # 如果设置的了机器人，就给机器人占座
            uid = robot

        if not seats.get(seat_str, None) in ["", None, uid]:
            return ApiErr(code=400, msg="座位已经有人了")

        for pos,_uid in seats.items():
            # 有可能换座位
            if _uid == uid :
                seats[pos] = ""
                break

        if not seats.get(seat_str, None) in ["", None, uid]:
            return ApiErr(code=400, msg="座位已经有人了")

        seats[seat_str] = uid
        cache.seats = seats

        return ApiOK(seats)
